package com.ruoyi.flow.flow.instance;

import com.ruoyi.flow.activiti.security.SecurityUtils;
import com.ruoyi.flow.common.Page;
import com.ruoyi.flow.core.response.Response;
import com.ruoyi.flow.flow.instance.InstanceQueryParam;
import com.ruoyi.flow.flow.workflow.FlowService;
import com.ruoyi.flow.flow.workflow.FlowTask;
import com.ruoyi.flow.flow.workflow.FlowUtils;
import org.activiti.engine.IdentityService;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

/**
 * 流程实例控制类
 *
 * @Author: wtian
 * @Description:
 * @Date: Created in 10:18 2018/8/17
 * @Version: 1.0
 */
@Controller
@RequestMapping("/flow/instances")
public class InstanceController {
    @Autowired
    private IdentityService identityService;

    /**
     * 启动流程
     *
     * @param assignees     办理人ID，多个用英文,隔开
     * @param assigneeType  办理人类型。{@code selectSingleUser}\{@code selectMultiUser}\{@code selectSingleGroup}\{@code selectMultiGroup}
     * @param definitionKey 模型定义标识
     * @param businessKey   业务标识
     */
    @RequestMapping(value = "/start/{definitionKey}", method = RequestMethod.POST)
    @ResponseBody
    public Response<FlowTask> startProcess(@PathVariable String definitionKey, @RequestParam Optional<String> businessKey, @RequestParam Optional<String> assignees, HttpServletRequest request) {
        String userId = SecurityUtils.getCurrentUserId();
        identityService.setAuthenticatedUserId(userId);

        String presentedBusinessKey = null;
        if (businessKey.isPresent()) {
            presentedBusinessKey = businessKey.get();
        }

        String presentedAssignees = null;
        if (assignees.isPresent() && StringUtils.isNotEmpty(assignees.get())) {
            presentedAssignees = assignees.get();
        }

        Map<String, Object> variables = FlowUtils.getProcessVariableFromRequest(request);
        try {
            ProcessInstance processInstance = FlowService.instanceService().startProcess(definitionKey, presentedBusinessKey, presentedAssignees, variables);
            TaskEntity executionEntity = FlowService.taskService().getLastExecutionTask(processInstance.getProcessInstanceId());
            return Response.<FlowTask>success().setData(new FlowTask(executionEntity));
        } catch (Exception e) {
            return Response.<FlowTask>error();
        }
    }

    /**
     * 跳转到我的申请页面
     *
     * @return
     */
    @RequestMapping
    public ModelAndView toMyCreatedPage(@RequestParam Optional<String> action) {
        String _action = "created";//我的申请
        if (action.isPresent()) {
            _action = action.get();
        }
        ModelAndView modelAndView = new ModelAndView("admin/instance/instances");
        modelAndView.addObject("title", "我的申请");
        modelAndView.addObject("action", _action);
        return modelAndView;
    }


    /**
     * 跳轉到流程歷史頁面
     *
     * @param taskId
     * @return
     */
    @RequestMapping(value = "/history/page", method = RequestMethod.GET)
    public ModelAndView toHistoryPage(@RequestParam Optional<String> taskId, @RequestParam Optional<String> instanceId) {
        String _instanceId = "";
        String _taskId = "";
        if (taskId.isPresent()) {
            _taskId = taskId.get();
            TaskEntity task = FlowService.taskService().getTaskByTaskId(_taskId);
            _instanceId = task.getProcessInstanceId();
        } else if (instanceId.isPresent()) {
            _instanceId = instanceId.get();
        }

//        List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(instanceId.get()).list();
        ModelAndView modelAndView = new ModelAndView("admin/task/history");
        modelAndView.addObject("historys", FlowService.instanceService().getTaskHistoryByProcessInstanceId(_instanceId, null).getRows());
        modelAndView.addObject("instanceId", _instanceId);
        modelAndView.addObject("taskId", _taskId);
        return modelAndView;
    }

    /**
     * 获取我的申请列表
     *
     * @param page 分页信息
     * @return
     */
    @RequestMapping(value = "/created")
    @ResponseBody
    public Page<FlowTask> myCreated(Page<FlowTask> page, InstanceQueryParam queryParam) {
        String userId = SecurityUtils.getCurrentUserId();
        if (queryParam == null) {
            queryParam = new InstanceQueryParam();
        }
        queryParam.setUserId(userId);
        return FlowService.instanceService().instanceList(page, queryParam);
    }
}
